package com.verlet.web;

import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * web启动类
 *
 * @author verlet
 */
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class WebApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }

    @Bean
    @LoadBalanced
    @SentinelRestTemplate
    public RestTemplate discoveryRestTemplate() {
        return setRestTempleEncode(new RestTemplate());
    }

    @Bean
    @SentinelRestTemplate
    public RestTemplate httpRestTemplate() {
        return setRestTempleEncode(new RestTemplate());
    }

    /**
     * 设置RestTemple编码为UTF-8
     */
    public RestTemplate setRestTempleEncode(RestTemplate restTemple) {
        if (null == restTemple || ObjectUtils.isEmpty(restTemple.getMessageConverters())) {
            return restTemple;
        }
        List<HttpMessageConverter<?>> messageConverters = restTemple.getMessageConverters();
        for (int i = 0; i < messageConverters.size(); i++) {
            HttpMessageConverter<?> httpMessageConverter = messageConverters.get(i);
            if (Objects.equals(httpMessageConverter.getClass(), StringHttpMessageConverter.class)) {
                messageConverters.set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
                break;
            }
        }
        return restTemple;
    }

}
